package com.ljf.controller;

import com.ljf.annotation.NoRequireLogin;
import com.ljf.entity.Menu;
import com.ljf.redis.RedisTemplateService;
import com.ljf.service.LoginService;
;
import com.ljf.util.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.constraints.NotEmpty;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@Validated
@Slf4j
public class LoginEmpController {

    @Autowired
    private LoginService loginService;
    @Autowired
    private RedisTemplateService redisTemplateService;
    @PostMapping("/login")
    @NoRequireLogin
    public Result<?> login(String username,  String password
    , HttpServletRequest request, HttpServletResponse response){
        //获取token
        String token = request.getHeader("token");
        HttpSession session = request.getSession();
        Object employee = session.getAttribute("employee");
        if (redisTemplateService.getCacheObject(token) != null && employee != null){
            //自动登录
            HashMap map = new HashMap<>();
            map.put("token",token);
            map.put("employee",employee);
            return Result.success(map);
        }else {
        Map<String,Object> map = loginService.login(username,password,request,response);
        return Result.success(map);
        }
    }

    @NoRequireLogin
    @GetMapping("/checkedToken")
    public Result checkedToken(String token){
        log.info("检查token:{}",token);
        Cookie cookie = new Cookie("token",token);
       Map<String,Object> map =  loginService.checkedToken(token);

       return Result.success(map);
    }

    /**
     * 查询登陆者拥有的菜单
     */

    @GetMapping("/empMenu")
    public Result empMenu(HttpServletRequest request){
        log.info("查询登录者拥有的菜单");
        List<Menu> menus = loginService.empMenu((String) request.getHeader("token"));
        return Result.success(menus);
    }

    /**
     * 退出功能
     * @param request
     * @return
     */
    @GetMapping("/exit")
    public Result exit(HttpServletRequest request){
        String token = request.getHeader("token");
        if (StringUtils.hasLength(token)){
            loginService.exit(token);
        }
        return Result.success();
    }
}
